package de.haw.shc.Szenario;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.*;
import de.haw.shc.Config.XML_Reader;
import de.haw.shc.Interfaces.DeviceProperty.Device;
import de.haw.shc.R;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: mizus
 * Date: 01.07.13
 * Time: 13:05
 * To change this template use File | Settings | File Templates.
 */
public class TimerSzenario extends Fragment {
	
	public interface TimerAbotDialog{
		public void showTimerAbortDialog();
		public boolean isNotificationCanceled();
	}

    private NumberPicker hPicker, mPicker;
    private Button lbl_Timer;
    private Map<String, List<Device>> roomMap;
    private Set<String> keySet;
    private Spinner roomSpinner;
    private TimerAbotDialog tAbortDialog;

    private CountDownTimer timer_util;
    
    private static final int TIMER_FINISH_NOTOFICATION_SLEEP_INTERVALL = 3000;
    private static final int TIMER_FINISH_NOTOFICATION_NUMBER = 20;

    public TimerSzenario(){
    }
    
	@Override
	public void onAttach(Activity activity){
		super.onAttach(activity);
		try{
			tAbortDialog = (TimerAbotDialog) activity;
		}catch(ClassCastException e){
			throw new ClassCastException(activity.toString()+" must implement TimerAbotDialog Interface");
		}
	}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        XML_Reader xml_reader = XML_Reader.createXMLReader(getResources());
        roomMap = xml_reader.getRaumMap();
        keySet = roomMap.keySet();

        View tView = inflater.inflate(R.layout.szenario_timer, container, false);

        hPicker = (NumberPicker) tView.findViewById(R.id.hours_picker);
        hPicker.setMaxValue(24);
        hPicker.setMinValue(0);

        mPicker = (NumberPicker) tView.findViewById(R.id.min_picker);
        mPicker.setMinValue(0);
        mPicker.setMaxValue(60);

        roomSpinner = (Spinner)tView.findViewById(R.id.combo_room);

        ArrayAdapter tmp = new ArrayAdapter(getActivity(), R.layout.spinner_item, fillSpinner(keySet));
        roomSpinner.setAdapter(tmp);
        roomSpinner.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

        lbl_Timer = (Button)tView.findViewById(R.id.btn_timer);
        lbl_Timer.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

        lbl_Timer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(timer_util != null){
                    timer_util.cancel();
                    timer_util = null;
                    lbl_Timer.setText("");
                }
            }
        });


        Button btn_ok = (Button)tView.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                action_timer();//To change body of implemented methods use File | Settings | File Templates.
            }
        });


        return tView;
    }

    private String[] fillSpinner(Set<String> keySet){
        String[] result = new String[keySet.size()+1];
        int i = 0;
        result[i] = getString(R.string.ueberall);
        for(String elem: keySet){
            i++;
            result[i] = elem;
        }
        return result;
    }


    void action_timer(){
       if (timer_util == null){
           int hour = hPicker.getValue();
           int min  = mPicker.getValue();

           lbl_Timer.setText(hour + " : " + min);



       final SzenarioNotifyHandler notifyHandler = new SzenarioNotifyHandler(roomMap, (String)roomSpinner.getSelectedItem());

           timer_util = new CountDownTimer((hoursToMillies(hour) + minToMillies(min)), 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int hours = milliesTohoures(millisUntilFinished);
                    int min =   milliesToMin(millisUntilFinished - hoursToMillies(hours));
                    int sek = milliesToSek((millisUntilFinished - (minToMillies(min) + hoursToMillies(hours))));
                    lbl_Timer.setText(hours +" : "+ min + " : " + sek);
                }

                @Override
                public void onFinish() {
                    tAbortDialog.showTimerAbortDialog();
                    new Thread(new Runnable(){

					@Override
					public void run() {
						int i = 0;
	                    while (i != TIMER_FINISH_NOTOFICATION_NUMBER && !tAbortDialog.isNotificationCanceled()){
	                    	int msg = (roomSpinner.getSelectedItem().equals(getString(R.string.ueberall)) ? SzenarioNotifyHandler.LIGHT_BLINK_ALL : SzenarioNotifyHandler.LIGHT_BLINK );              	
	                    	notifyHandler.sendEmptyMessage(msg);
	                    	try {
								Thread.sleep(TIMER_FINISH_NOTOFICATION_SLEEP_INTERVALL);
							} catch (InterruptedException e) {
								Log.d("InterruptedExcetion", e.getMessage());
								e.printStackTrace();
							}
	                    }
					}
				}).start();
            }
        };
        timer_util.start();
    }
    }

    private int hoursToMillies(int hours){
        return 60 * minToMillies(hours);
    }

    public int minToMillies(int min){
        return 60 * min * 1000;
    }

    public int milliesToMin(long millis){
        return milliesToSek(millis)/60;
    }

    public int milliesToSek(long millis){
        return (int) millis/1000;
    }

    public int milliesTohoures(long millies){
        return milliesToMin(millies)/60;
    }
}

